<template>
  <div style="background: #fff;display: flex;justify-content: space-between;">
    <div>
      <a-tag 
        v-for="t in tagsViews" 
        closable 
        @click="toPath(t.fullPath)" 
        @close="e => closeSelectedTag(e, t)"
        :color="isActive(t)?'#1890ff':'gray'"
        style="margin-bottom: 5px"
        :key="t.name">{{ t.name }}</a-tag>
    </div>
    <a-tag color="#f50" @click="closeALlTag">关闭全部</a-tag>
  </div>
</template>

<script>
export default {
  data () {
    return {
      tagsViews: []
    }
  },
  watch: {
    $route() {
      this.addViewTags();
    },
    tagsViews (val) {
      this.$store.dispatch('app/setTagView', val.map(r => r.name))
    }
  },
  mounted() {
    this.addViewTags();
  },
  methods: {
    isActive(route) {
      return route.name === this.$route.name;
    },
    addViewTags() {
      const { name } = this.$route
      if (name) {
        if (!this.tagsViews.find(t => t.name === name)) {
          this.tagsViews.push(this.$route)
        }
      }
    },
    toPath (path) {
      this.$router.push(path)
    },
    closeSelectedTag(e, view) {
      console.log(view)
      e.stopPropagation();
      let selectedIndex = this.tagsViews.findIndex(t => view.name === t.name)
      let length = this.tagsViews.length
      if(view.name === this.$route.name){
        if(selectedIndex == 0 && length == 1){
          this.$router.push('/personal')
        }else{
          this.$router.go(-1)
        }
      }
      this.tagsViews.splice(selectedIndex, 1)
    },
    closeALlTag () {
      if (this.tagsViews.length === 1 && this.tagsViews[0].path === '/personal') {
        return
      }
      this.tagsViews = []
      this.$router.push('/personal')
    }
  }
};
</script>

<style>
</style>